package Levels;

import Questions.Question;
import Session.UserAnswers;
import java.util.ArrayList;
import java.util.Collections;


/**
 * Created by:
 * User: Igor Martynovich and Guzenko Igor
 * Date: 21.11.13
 */
public class Chapter {
    public static final int COUNT_IN_LEVEL=4;
    private Complexity currentComplexity;
    private ArrayList<Question> easyQuestions;
    private ArrayList<Question> mediumQuestions;
    private UserAnswers userLevelAnswers;




    public Chapter(){
        easyQuestions = new ArrayList<>();
        mediumQuestions = new ArrayList<>();
        userLevelAnswers = new UserAnswers(COUNT_IN_LEVEL);
    }

    public void addQuestion(Complexity complexity,Question question){
       if(complexity.equals(Complexity.EASY)){
             easyQuestions.add(question);
            } else {
             mediumQuestions.add(question);
       }
    }

    public void askQuestion(int index){
        index=getCheckedIndex(index);
        if(mediumQuestions.isEmpty()){
            System.out.println("EMPTY MEDIUM QNS");
            return;
        }
        if(currentComplexity.equals(Complexity.EASY)){
             easyQuestions.get(index).askQuestion();
         }else {
             mediumQuestions.get(index).askQuestion();
         }
    }

    public void setCurrentComplexity(Complexity currentComplexity) {
        this.currentComplexity = currentComplexity;
    }

    public void setUserLevelAnswer(int key,String answer) {
        this.userLevelAnswers.setAnswer(key,answer);
    }

    private int getCheckedIndex(int index){
        if(index<0){
            index=0;}
        else if(index>=COUNT_IN_LEVEL){
            index=COUNT_IN_LEVEL-1;
        }
        return index;
    }

    public boolean isAnswered(){
        return this.userLevelAnswers.isAnsweredAll();
    }

    public int getLevelResult() {
          int levelResult=0;
          if(userLevelAnswers.isAnsweredAll()){
            for(int index=0; index<COUNT_IN_LEVEL; index++){
              if( getQuestionByComplexity(index).isCorrect(userLevelAnswers.getAnswer(index)))
                  levelResult++;
            }
          }
        userLevelAnswers.clearAnswers();
        return levelResult;
    }

    private Question getQuestionByComplexity(int index){
        Question question;
        if (currentComplexity.equals(Complexity.EASY)){
           question = easyQuestions.get(index);
        } else {
            question = mediumQuestions.get(index);
        }
        return question;
    }

    public Complexity getComplexity() {
        return currentComplexity;
    }

    public void shuffleChapterLevel(){
        if(currentComplexity.equals(Complexity.EASY)){
            Collections.shuffle(easyQuestions);
        }
        else {
            Collections.shuffle(mediumQuestions);
        }
    }
}
